const Service = require('egg').Service

class CourseService extends Service {
  async index(body) {
    const { ctx, app } = this
    const { categoryId, channelId } = body
    // 获取当前课程
    const curCourse = await ctx.find('Course', { where: { categoryId }}, 'findAll')
    const tmp = []
    if (curCourse.length > 0) {
      curCourse.forEach(item => {
        tmp.push(item.dataValues)
      })
    }
    // 获取当前类别
    const curCategory = await ctx.find('CourseCategory', { where: { categoryId }, attributes: ['categoryName'] })
    // 添加任务队列
    const taskId = await ctx.service.cache.task.addTask()
    // 请求接口
    const courseUrl = `${app.config.moocDomain}/web/j/mocSearchBean.searchCourseCardByChannelAndCategoryId.rpc?csrfKey=${app.config.moocCookie.NTESSTUDYSI}`
    let count = -200
    let pageIndex = 1
    let num = 0
    if (categoryId && channelId) {
      const postData = {
        categoryId,
        categoryChannelId: channelId,
        orderBy: 0,
        pageSize: 31
      }
      while (count === -200 || count > 0) {
        postData.pageIndex = pageIndex
        const res = await ctx.helper.curlPost(courseUrl, {
          mocCourseQueryVo: JSON.stringify(postData)
        })
        if (res.data.code === 0) {
          if (count === -200) {
            count = res.data.result.query.totleCount - postData.pageSize
          } else {
            count -= postData.pageSize
          }
          if (res.data.result) {
            const updateCount = await this.createCourse(res.data.result.list, channelId, categoryId, tmp)
            num += updateCount
          }
        } else {
          count = -1
          break
        }
        pageIndex++
      }
      await ctx.service.cache.index.addLog(categoryId, num, 1)
      await ctx.service.cache.task.updateTaskData({
        taskId,
        num,
        finished: true,
        title: curCategory.dataValues.categoryName
      })
      return { taskId, num }
    }
    return { taskId, num }
  }

  async createCourse(data, channelId, categoryId, courses) {
    const { ctx, app } = this
    const postData = []
    for (let i = 0, len = data.length; i < len; i++) {
      if (data[i].mocCourseBaseCardVo) {
        const params = data[i].mocCourseBaseCardVo
        const { currentTermId, id, name, bigPhoto, teacherId, teacherName, schoolSN, schoolName, startTime, endTime } = params
        const dict = {
          channelId,
          categoryId,
          termId: currentTermId,
          courseId: id,
          name,
          bigPhoto,
          teacherId,
          teacherName,
          schoolSN,
          schoolName,
          startTime: new Date(+startTime),
          endTime: new Date(+endTime)
        }
        // 获取评价数量和平均评分
        const evaluateUrl = `${app.config.moocDomain}/web/j/mocCourseV2RpcBean.getEvaluateAvgAndCount.rpc?csrfKey=${app.config.moocCookie.NTESSTUDYSI}`
        const evaluateRes = await ctx.helper.curlPost(evaluateUrl, {
          courseId: params.id
        })
        if (evaluateRes.data.code === 0) {
          try {
            const { evaluateCount, avgMark } = evaluateRes.data.result
            dict.evaluateCount = evaluateCount
            dict.avgMark = avgMark
          } catch (error) {
            dict.evaluateCount = 0
            dict.avgMark = 0
          }
        }
        const index = courses.findIndex(course => +course.courseId === +id)
        if (index !== -1) {
          if (courses[index].evaluateCount + '' !== dict.evaluateCount + '' || courses[index].avgMark + '' !== dict.avgMark + '') {
            dict.id = courses[index].id
            postData.push(dict)
          }
        } else {
          postData.push(dict)
        }
      }
    }
    if (postData.length > 0) {
      const res = await ctx.bulkCreate('Course', postData, { updateOnDuplicate: ['evaluateCount', 'avgMark'] })
      return res.length
    }
    return 0
  }

  // 添加课程爬取记录
  async addCourseLog(categoryId, count, type) {
    const { ctx } = this
    const res = await ctx.find('CourseCategory', {
      where: {
        categoryId
      },
      attributes: ['categoryName']
    })
    if (res) {
      const data = res.dataValues
      const postData = {
        name: data.categoryName,
        type,
        count
      }
      await ctx.service.cache.index.addLog(postData)
    }
  }
}

module.exports = CourseService
